package cn.stylefeng.guns.sys.core.util;
import java.security.MessageDigest;
import java.util.*;

/**
 * @author liuy
 */
public class Md5Util {
    /***
     * MD5加密 生成32位md5码(大写)
     * @return 返回32位md5码(大写)
     */
    public static String md5(String inStr) throws Exception {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }

        byte[] byteArray = inStr.getBytes("UTF-8");
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString().toUpperCase();
    }

    /***
     * MD5加密 生成32位md5码(小写)
     * @return 返回32位md5码(小写)
     */
    public static String md5s(String inStr) throws Exception {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }

        byte[] byteArray = inStr.getBytes("UTF-8");
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString().toLowerCase();
    }
    /**
     * 字段按键值对的形式加&符号拼接 由小到大排列
     * @param info
     * @return
     * @throws Exception
     */
    public static String putPairsSequenceAndTogether(Map<String, String> info) throws Exception {
        List<Map.Entry<String, String>> infoIds = new ArrayList<>(info.entrySet());
        Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
            @Override
            public int compare(Map.Entry<String, String> arg0, Map.Entry<String, String> arg1) {
                return (arg0.getKey()).compareTo(arg1.getKey());
            }
        });
        String ret = "";
        for (Map.Entry<String, String> entry : infoIds) {
            ret += entry.getKey();
            ret +="=";
            ret += entry.getValue();
            ret += "&";
        }
        ret = ret.substring(0, ret.length() - 1).toLowerCase();

        String sign=md5s(ret);
        System.out.println("ret:"+ret);
        //ret=ret+"&md5_code="+sign;
        return sign;
    }




}